#include <QSettings>
#include <QtDebug>

#include "connection.h"
#include "connect.h"
#include "ui_connect.h"

Connect::Connect(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Connect)
{
    ui->setupUi(this);

    // add menu settings
    ui->HostBox->setVisible(false);
    layout()->setSizeConstraint(QLayout::SetFixedSize);

    // load save settings
    QSettings *settings = new QSettings("techdep.conf",QSettings::IniFormat);
    ui->UserNameEdit->setText( settings->value("logon/login",tr("input login")).toString());
    ui->HostEdit->setText( settings->value("logon/host",tr("input host")).toString());
    ui->PortEdit->setText( settings->value("logon/port",tr("input port")).toString());
    ui->DatabaseEdit->setText( settings->value("logon/database",tr("input name database")).toString());

}

Connect::~Connect()
{
    // save
    QSettings *settings = new QSettings("techdep.conf",QSettings::IniFormat);
    settings->setValue("logon/db","QPSQL");
    settings->setValue("logon/login",ui->UserNameEdit->text());
    settings->setValue("logon/host",ui->HostEdit->text());
    settings->setValue("logon/port",ui->PortEdit->text());
    settings->setValue("logon/database",ui->DatabaseEdit->text());
    settings->sync();

    delete ui;
}

bool Connect::createConnection(QString user, QString password, QString host, QString database, int port)
{
    QSqlDatabase db;
    db = QSqlDatabase::addDatabase("QPSQL");
    db.setHostName(host);
    db.setPort(port);
    db.setDatabaseName(database);
    db.setUserName(user);
    db.setPassword(password);

    qDebug() << tr(" -------- Connect ---------") << endl
             << tr("host: ") <<db.hostName() << endl
             << tr("port: ") << db.port() << endl
             << tr("database: ") << db.databaseName() << endl
             << tr("user: ") << db.userName();

    if (!db.open()) {
        QMessageBox::critical(0, tr("Cannot open database"),
            db.lastError().text(), QMessageBox::Cancel);
        qDebug() << db.lastError().text();
        return false;
    }

    emit Connected();

    return true;
}


void Connect::on_MoreButton_clicked()
{
    ui->HostBox->setVisible(!ui->HostBox->isVisible());
}

void Connect::on_ConnectButton_clicked()
{
    createConnection(ui->UserNameEdit->text(),ui->PasswordEdit->text(),ui->HostEdit->text(),ui->DatabaseEdit->text(),ui->PortEdit->text().toInt());
    //if (!createConnection())
    //    return 1;

    close();

}
